import { fetchEventSource } from '@microsoft/fetch-event-source'
export const useEventSource = async (url: string, body: object, callback: Function) => {
    const loadingInstance = ElLoading.service({
        lock: false,
        target:'#rightbar',
        text: '智能生成中...',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    setTimeout(() => {
        loadingInstance.close()
    }, 6000)

    const appConfig = useAppConfig()
    const apiUrl = appConfig.app.apiUrl
    const store = useUserStore();
    await fetchEventSource(apiUrl + url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            "token": store.userInfo.token,
        },
        body: JSON.stringify(body),
        onmessage(event) {
            if (event.data === "[DONE]") {
                console.log('done')
            } else {
                const data = JSON.parse(event.data)
                callback(data)
            }
        },
        onclose() {
            ElMessage.success('生成成功')
            console.log('close')
        },
        onerror(error) {
            console.log('error', error)
            throw error
        }
    })

}